var prefix = ctx + "sys/user";
$(function() {
	var deptId = '';
	load();
});

function load(){
	layui.use(['form','table'], function() {
		var form = layui.form ,
			table = layui.table;//载入table模块
		var searchParams = {};
		searchParams['search_eq_userType']=7;
		searchParams['search_like_keyword']=$('#keyword').val();
		searchParams['search_eq_townId']=$('#townId').val();
		searchParams['search_eq_villageId']=$('#villageId').val();
		searchParams['checkType']=$('#checkType').val();
		searchParams['userLevel']=$('#userLevel').val();

		form.on('select(townId)', function (data) {
			console.log('townId',data.value);
			getVillages(data.value,form)
		});

		//初始化table
		table.render({
			elem: '#exampleTable',//承载数据的table Id
			url: prefix + "/baobao_list",//请求数据连接
			toolbar: '#toolbarDemo',
			cellMinWidth: 80,//全局定义所有常规单元格的最小宽度（默认：60）
			even: true,//是否开启隔行变色
			loading:true,//是否显示加载条

			where :{
				searchParams:searchParams,
				sorts:{},
			},
			//page: true,//是否分页
			page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
				layout: [ 'prev', 'page', 'next', 'skip', 'count','limit'] //自定义分页布局
			},
			cols: [[
				{ checkbox : true },
				{ field : 'userId',  align : 'center', title : '序号'  },
				{ field : 'name', align : 'center', title : '姓名' },
				{ field : 'username', align : 'center', title : '用户名' },
				{ field : 'mobile', align : 'center', title : '手机号' },
				{ field : 'roleName', align : 'center', title : '角色',
					templet : function(item) {
						if (item.checkType === 0) {
							return '<span class="label label-warning">包保责任人</span>';
						} else if (item.checkType === 1) {
							return '<span class="label label-primary">督导巡查人</span>';
						}
					}
				},
				{ field : 'userLevel', align : 'center', title : '账号等级',
					templet : function(item) {
						if (item.userLevel === 1) {
							return '<span class="label label-info">县级账号</span>';
						} else if (item.userLevel === 2) {
							return '<span class="label label-primary">镇级账号</span>';
						} else if (item.userLevel === 3) {
							return '<span class="label label-warning">村级账号</span>';
						}else{
							return item.userLevel;
						}
					}
				},
				{ field : 'status', title : '状态', align : 'center',
					templet : function(value) {
						if (value.status == '0') {
							return '<span class="label label-danger">禁用</span>';
						} else if (value.status == '1') {
							return '<span class="label label-primary">正常</span>';
						}
					}
				},
				{ field : 'wxNickName', align : 'center', title : '微信用户' },
				{ field : 'townName1', align : 'center', title : '乡镇名称' },
				{ field: 'villageName1',align : 'center', title:'村居名称'},
				{ title: '操作', minWidth: 50, templet: '#currentTableBar', fixed: "right", align: "center"}
			]],
			id: 'currentTableId',//表格Id
			done: function(res, curr, count){
				// $('.layui-table-fixed-r').removeClass('layui-hide');
			} //解决最右侧列不能固定的问题
		});
		/**
		 * 操作栏tool  监听事件
		 */
		table.on('tool(currentTableFilter)', function (obj) {
			console.log('obj',obj.data)
			if (obj.event === 'edit') {  // 监听添加操作
				edit(obj.data.userId);
			} else if (obj.event === 'delete') {  // 监听删除操作
				remove(obj.data.userId);
			}
		});
		form.on('switch(status)', function(data){
			// 得到开关的value值，实际是需要修改的ID值。
			var id = data.value;
			var status = this.checked ? '1' : '0';
			console.log('data',data)
			console.log('id',id)
			console.log('status',status)
			$.ajax({
				url : ctx + "sys/user/updateSendMsg",
				type : "post",
				data : {
					'userId' : id,
					'isSendMsg' : status
				},
				success : function(r) {
					if (r.code == 0) {
						layer.msg(r.msg);
						reLoad();
					} else {
						layer.msg(r.msg);
					}
				}
			});
		});
		// 监听搜索操作
		form.on('submit(data-search-btn)', function (data) {
			//执行搜索重载
			reLoad();
			return false;
		});

		/**
		 * 操作栏tool  监听事件
		 */
		table.on('toolbar(currentTableFilter)', function (obj) {
			if (obj.event === 'add') {  // 监听添加操作
				add();
			} else if (obj.event === 'delete') {  // 监听删除操作
				var checkStatus = table.checkStatus('currentTableId')
					, data = checkStatus.data;
				layer.alert(JSON.stringify(data));
			}else if (obj.event === 'back') {  // 监听添加操作
				goBack();
			}
			else if(obj.event === 'upload_user'){
				batchAdd()
			}
		});
	});
}


function batchAdd() {
	var index = layer.open({
		type : 2,
		title : '批量增加',
		maxmin : true,
		shadeClose : false, // 点击遮罩关闭层
		area : [ '800px', '320px' ],
		content : ctx + 'module/citizen/goBatchAddAdmin' // iframe的url
	});
}

function goBack(){
	window.location.href= ctx + "module/shop";
}

function reLoad() {
	var userType = $('#userType').val();
	var searchParams = {};
	searchParams['search_eq_userType']= 7;
	searchParams['search_like_keyword']=$('#keyword').val();
	searchParams['search_eq_townId']=$('#townId').val();
	searchParams['search_eq_villageId']=$('#villageId').val();
	searchParams['checkType']=$('#checkType').val();
	searchParams['userLevel']=$('#userLevel').val();
	layui.use(['table'], function() {
		var table = layui.table;//载入table模块

		var  page = $(".layui-laypage-skip").find("input").val() //当前页码值
		console.log('page',page)
		table.reload('currentTableId', {
			page: {curr: page},
			where: {searchParams:searchParams}
		}, 'data');
	});
}


function getVillages(townId,form) {
	$.ajax({
		url : ctx + "module/citizen/villages",
		type : "post",
		data:{
			townId:townId
		},
		success : function(r) {
			console.log('r',r)
			if (r.code==0) {
				console.log("villages",r.villages);
				var villages = r.villages;
				if (villages.length > 0) {
					$('#villageId').empty();
					$('#villageId').append(new Option('请选择村居', ''));
					for (var i = 0; i < villages.length; i++) {
						$('#villageId').append(new Option(villages[i].townName, villages[i].id));
					}
				} else {
					$('#villageId').empty();
					$('#villageId').append(new Option('暂无村居', ''));
				}
				form.render("select");
			}
		}
	});
}


function add() {
	var userType = $('#userType').val();
	// iframe层
	layer.open({
		type : 2,
		title : '增加用户',
		maxmin : true,
		shadeClose : false, // 点击遮罩关闭层
		area : [ '800px', '600px'],
		content : prefix + '/addBaoBao'
	});
}

function remove(id) {
	layer.confirm('确定要删除选中的记录？', {
		btn : [ '确定', '取消' ]
	}, function() {
		$.ajax({
			url : ctx +"sys/user/remove/baobao",
			type : "post",
			data : {
				'id' : id
			},
			success : function(r) {
				if (r.code == 0) {
					layer.msg(r.msg);
					reLoad();
				} else {
					layer.msg(r.msg);
				}
			}
		});
	})
}
function edit(id) {
	layer.open({
		type : 2,
		title : '用户修改',
		maxmin : true,
		shadeClose : false,
		area : [ '800px', '600px' ],
		content : prefix + '/editBaoBao/' + id // iframe的url
	});
}
function resetPwd(id) {
	layer.open({
		type : 2,
		title : '重置密码',
		maxmin : true,
		shadeClose : false, // 点击遮罩关闭层
		area : [ '400px', '260px' ],
		content : prefix + '/resetPwd/' + id // iframe的url
	});
}
function batchRemove() {
	var rows = $('#exampleTable').bootstrapTable('getSelections'); // 返回所有选择的行，当没有选择的记录时，返回一个空数组
	if (rows.length == 0) {
		layer.msg("请选择要删除的数据");
		return;
	}
	layer.confirm("确认要删除选中的'" + rows.length + "'条数据吗?", {
		btn : [ '确定', '取消' ]
	// 按钮
	}, function() {
		var ids = new Array();
		// 遍历所有选择的行数据，取每条数据对应的ID
		$.each(rows, function(i, row) {
			ids[i] = row['userId'];
		});
		$.ajax({
			type : 'POST',
			data : {
				"ids" : ids
			},
			url : prefix + '/batchRemove',
			success : function(r) {
				if (r.code == 0) {
					layer.msg(r.msg);
					reLoad();
				} else {
					layer.msg(r.msg);
				}
			}
		});
	}, function() {});
}
